package com.qianchang.microfinance.view.home.cash;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.bigkoo.pickerview.model.IPickerViewData;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.BaseTextWatcher;
import com.dm.library.widgets.ClearEditText;
import com.dm.library.widgets.OneLineLinearLayout;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.ApplyLoanDayListBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.LoanParamsBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.LoanUsageBean;
import com.qianchang.microfinance.bean.Product;
import com.qianchang.microfinance.bean.ProductBean;
import com.qianchang.microfinance.bean.ProductConfigBean;
import com.qianchang.microfinance.bean.ProjectStatus;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.bean.event.AgreementTitleBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.credit.data.ConfirmInfoJinbaoActivity;
import com.qianchang.microfinance.view.credit.data.ContractInfoActivity;
import com.qianchang.microfinance.view.dialog.CommonDialog;
import com.qianchang.microfinance.view.mine.UserSupplActivity;
import com.qianchang.microfinance.view.mine.loan.ConfirmAgreementActivity;
import com.qianchang.microfinance.view.mine.loan.LoanProgressActivity;
import com.qianchang.microfinance.view.mine.loan.RepayPlanActivity;
import com.qianchang.microfinance.view.product.ProductFragment;
import com.qianchang.microfinance.view.register.AgreementActivity;
import com.qianchang.microfinance.view.register.AgreementApi;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: 申请借款，现金贷（金宝贷），学生贷 业主贷；都用这个
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/14 11:11
 */
public class ApplyCashActivity extends BaseActivity implements CommonDialog.OnItemSelectListener {

    private static final int PAYBACK_METHOD = 0;
    private static final int PAYBACK_DEADLINE = 1;
    private static final int LOAN_USAGE = 2;
    private static final String TAG = "ApplyCashActivity";
    public static final String LOAN_PARAMS = "loan_params";

    @BindView(R.id.oll_payback_type)
    OneLineLinearLayout ollPaybackMethod;
    @BindView(R.id.oll_apply_date)
    OneLineLinearLayout ollApplyDate;
    @BindView(R.id.oll_payback_plan)
    OneLineLinearLayout ollPaybackPlan;
    @BindView(R.id.tv_protocol)
    TextView tvProtocol;
    @BindView(R.id.et_loan_amount)
    ClearEditText etLoanAmount;
    @BindView(R.id.oll_all_interest_rate)
    OneLineLinearLayout ollAllInterestRate;
    @BindView(R.id.oll_interest_rate)
    OneLineLinearLayout ollInterestRate;
    @BindView(R.id.oll_loan_fee)
    OneLineLinearLayout ollLoanFee;
    @BindView(R.id.ck_protocol)
    CheckBox ckProtocol;
    @BindView(R.id.tv_right)
    DTextView tvRight;
    @BindView(R.id.oll_loan_usage)
    OneLineLinearLayout ollloanUsage;

    private int loanUsageInt = -1;
    private String paybackMode;//还款方式
    private ProductConfigBean productConfigBean;//配置

    //申请借款参数
    private String deadlinekey;//对于月就是 "1"；对于日 "1-20"///
    private String unit;//借款单位
    private String serviceFeeRate;//服务费率//就是月利率
    private String gradeId;//用户等级
    private double loanAmount;//借款金额
    private double allInterestRate;//总利息
    private double monthRate;//就是月利率
    private String productType = "0";  //获取产品常量的参数
    private String productId = "00101522744129177104"; //获取产品常量的参数
    private String strRate;//日利率  月利率；
    private int paybackPeriod;//还款天或者月数
    private List<ProductConfigBean.RepaymentTypeBean> repaymentTypeList;
    private double dailyRate;
    private String lastProductUpdateTime;   //最后跟新时间
    private int daysPerMonth;               //日利率
    private String serviceFeeSetting;       //服务费费率
    private double loanLimit;
    private double applyMoneyStart;
    private double applyMoneyEnd;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_cash);
        ButterKnife.bind(this);
        initView();
        initData();
    }


    @Override
    protected void initView() {
        super.initView();
        etLoanAmount.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                loanAmount = StringUtils.toDouble(s.toString().trim());
                if (paybackPeriod != 0) {//说明已经选择了还款期限
                    initInterest();
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();//首页点击借款
        if (bundle != null) {//产品列表点击借款
            ProductBean bean = (ProductBean) bundle.getSerializable(ProductFragment.PRODUCT_BEAN);
            Product project = (Product) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_PROJECT);
            FindUserBasicInfoBean findUserBasicInfoBean = (FindUserBasicInfoBean) bundle.getSerializable(ConstantAppInfo.BASIC_INFO_BEAN);

            if (null != findUserBasicInfoBean) {
                loanLimit = findUserBasicInfoBean.getLoanLimit();
            }
            if (bean != null) {
                productType = bean.getProductType();
                productId = bean.getProductId();
            }
            if (project != null) {
                productType = project.getProductType();
                productId = project.getProductId();
            }
        }
        //产品介绍
        if (!"0".equals(productType)) {
            initProductIntrduce();
        } else {
            tvRight.setVisibility(View.GONE);
        }
        getConstantInfo();
        JSONArray ja = new JSONArray();
        ja.put(productType);
        ja.put("8");
        ja.put("9");
        AgreementApi.getAgreementName(this, ja, new AgreementApi.AgreementNameCallBack() {
            @Override
            public void success(List<AgreementTitleBean> agreementName) {
                if (agreementName != null && agreementName.size() >= 3) {
                    AgreementTitleBean agreementOne = agreementName.get(0);
                    AgreementTitleBean agreementTwo = agreementName.get(1);
                    AgreementTitleBean agreementThree = agreementName.get(2);

                    tvProtocol.setMovementMethod(LinkMovementMethod.getInstance());
                    tvProtocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
                    SpanUtils spanUtils = new SpanUtils();
                    spanUtils.append(getString(R.string.Label_reading)).setForegroundColor(getResources().getColor(R.color.common_black_color_6)).append("《" + agreementOne.getAgreementName() + "》")
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, productType);
                                    startActivity(AgreementActivity.class, bundle);
                                }

                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    ds.setColor(getResources().getColor(R.color.common_blue_color_light));            //  R.color.common_orange_color_light
                                    ds.setUnderlineText(false);
                                }

                            })
                            .append("《" + agreementTwo.getAgreementName() + "》")
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    ds.setColor(getResources().getColor(R.color.common_blue_color_light));              //R.color.common_orange_color_light
                                    ds.setUnderlineText(false);
                                }

                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "8");
                                    startActivity(AgreementActivity.class, bundle);
                                }
                            })
                            .append("《" + agreementThree.getAgreementName() + "》")
                            .setClickSpan(new ClickableSpan() {
                                @Override
                                public void updateDrawState(TextPaint ds) {
                                    ds.setColor(getResources().getColor(R.color.common_blue_color_light));            //R.color.common_orange_color_light
                                    ds.setUnderlineText(false);
                                }

                                @Override
                                public void onClick(View widget) {
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "9");
                                    startActivity(AgreementActivity.class, bundle);
                                }
                            });

                    tvProtocol.setText(spanUtils.create());
                }


            }
        });
    }

    private void initProductIntrduce() {
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setTextContent(getString(R.string.Label_product_intrduce));
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle_product = new Bundle();
                bundle_product.putString(ConstantAppInfo.PROJECT_ID, productId);
                bundle_product.putString(ConstantAppInfo.PROJECT_TYPE, productType);
                startActivity(ProductIntroduceActivity.class, bundle_product);
            }
        });
    }

    private void getConstantInfo() {
        show();
        HttpParams params = new HttpParams();
        params.put("productType", productType); //产品类型
        params.put("productId", productId); //产品Id
        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/product/" + LoanType.getNameByType(productType) + DMConstant.Config.V + "/getConfig.do", params, new RequestCallBack<ProductConfigBean>() {

            @Override
            public void onSuccess(JsonResult<ProductConfigBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    productConfigBean = response.getObject();
                    if (null != productConfigBean) {
                        repaymentTypeList = productConfigBean.getRepaymentType();
                        lastProductUpdateTime = productConfigBean.getProductInfo().getUpdateTime();
                        daysPerMonth = productConfigBean.getDaysPerMonth();
                        serviceFeeSetting = productConfigBean.getProductInfo().getServiceFeeSetting();
                        refreshUi();
                    }
                } else {
                    ToastUtil.getInstant().show(ApplyCashActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ApplyCashActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    private void refreshUi() {
        ProductConfigBean.ProductInfoBean productInfo = productConfigBean.getProductInfo();
        setTitleName(productInfo.getProductName());
        ollLoanFee.setRightContent(FormatUtil.get2Double(productInfo.getBorrowFeeRate() * 100) + "%");
        if (loanLimit == 0) {
            applyMoneyStart = productInfo.getApplyMoneyStart();
            applyMoneyEnd = productInfo.getApplyMoneyEnd();
            etLoanAmount.setHint("借款范围" + FormatUtil.numKbPointFormat(applyMoneyStart) + "~" + FormatUtil.numKbPointFormat(applyMoneyEnd));
        } else {
            etLoanAmount.setHint("最大可借额度" + loanLimit);
        }
    }

    @OnClick({R.id.oll_payback_type, R.id.oll_apply_date, R.id.oll_payback_plan, R.id.tv_protocol, R.id.btn_apply_loan,R.id.oll_loan_usage})
    public void onViewClicked(View view) {
        int id = view.getId();
        loanAmount = StringUtils.toInt(etLoanAmount.getText().toString().trim(), 0);
        switch (id) {
            case R.id.oll_payback_plan://借款计划
                checkAndgotoLoanPlan();
                break;
            case R.id.tv_protocol:
                loanAgreement();
                break;
            case R.id.btn_apply_loan://申请借款

//                startLoan();  //2018.2.1 注释迪蒙代码

                if(loanAmount % 1000 != 0){
                    ToastUtil.getInstant().show(getApplicationContext(),"请输入贷款金额为一千的整数倍！");
                }else if(loanLimit <= 0){
                    ToastUtil.getInstant().show(getApplicationContext(),"您的贷款额度为0，不能借款！");
                }else{
                    startLoan();
                }
                /*if(loanAmount % 1000 == 0 && loanLimit > 0 ){     //如果是1千倍数开始给贷款
                        startLoan();
                }else {
                    ToastUtil.getInstant().show(getApplicationContext(),"请输入贷款金额为一千的整数倍或额度要大于0");
                }*/
                break;
            default:
                clickDialog(id);
                break;
        }
    }





    //借款协议
    private void loanAgreement() {
        Bundle bundle = new Bundle();
        bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, productType);
        startActivity(AgreementActivity.class, bundle);
    }

    //金保贷
    private void startLoan() {
//        if ("0".equals(productType)) {
            if (!checkJinbaoLoan()) {
                return;
            }
            //先检查
        loanCashCheck();

            //loanCash();
//        } else {
//            if (!checkOtherLoan()) {
//                return;
//            }
//            //loanOthers();
//        }
    }

    private boolean checkOtherLoan() {
        if (productConfigBean == null) {
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.data_error));
            return false;
        }

        if (loanAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
            return false;
        }

        if (loanAmount > applyMoneyEnd) {
            ToastUtil.getInstant().show(this, "借款金额不能大于最大借款额度");
            return false;
        }

        if (loanAmount < applyMoneyStart) {
            ToastUtil.getInstant().show(this, "借款金额不能小于最小借款额度");
            return false;
        }

        if (TextUtils.isEmpty(paybackMode)) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
            return false;
        }
        if (0 == paybackPeriod) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_deadline));
            return false;
        }

        if (!ckProtocol.isChecked()) {
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.msg_read_loan_agreement));
            return false;
        }
        return true;
    }

    private void loanOthers() {

        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/project/" + LoanType.getNameByType(productType) + DMConstant.Config.V + "/getAdvancedProjectId.do", params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                if (response.isReqDataSuccess()) {
                    String currentId = response.getObject();
                    Bundle bundle = new Bundle();

                    LoanParamsBean loanParamsBean = new LoanParamsBean();
                    loanParamsBean.setApplyAmount(String.valueOf(loanAmount));
                    loanParamsBean.setDeadlinekey(deadlinekey);
                    loanParamsBean.setDeadline(String.valueOf(paybackPeriod));
                    loanParamsBean.setUnit(unit);
                    loanParamsBean.setProductType(productType);
                    loanParamsBean.setProductId(productId);
                    loanParamsBean.setCurrentId(currentId);
                    loanParamsBean.setRepaymentType(paybackMode);
                    loanParamsBean.setServiceFeeRate(serviceFeeRate);
                    loanParamsBean.setLastProductUpdateTime(lastProductUpdateTime);
                    loanParamsBean.setGradeId(gradeId);
                    loanParamsBean.setDaysPerMonth(String.valueOf(daysPerMonth));
                    loanParamsBean.setServiceFeeSetting(serviceFeeSetting);
                    bundle.putSerializable(LOAN_PARAMS, loanParamsBean);
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle, true);

                } else {
                    ToastUtil.getInstant().show(ApplyCashActivity.this, response.getDescription());
                }

            }
            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(ApplyCashActivity.this, msg);

            }
            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void loanCashCheck() {
        show();
        HttpParams params = new HttpParams();
        params.put("applyAmount", loanAmount);
        params.put("deadlinekey", deadlinekey);
        params.put("deadline", paybackPeriod);
        params.put("unit", unit);
        params.put("productType", productType);
        params.put("productId", productId);
        params.put("repaymentType", paybackMode);
        params.put("serviceFeeRate", monthRate);
        params.put("lastProductUpdateTime", lastProductUpdateTime);
        params.put("gradeId", gradeId);
        params.put("daysPerMonth", daysPerMonth);//日利率
        params.put("serviceFeeSetting", serviceFeeSetting);
        params.put("purpose",loanUsageInt);

        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.PROJECT_CHECK, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    //参数直接传递
                    Bundle bundle = new Bundle();
                    bundle.putDouble("applyAmount", loanAmount);
                    bundle.putString("deadlinekey", deadlinekey);
                    bundle.putInt("deadline", paybackPeriod);
                    bundle.putString("unit", unit);
                    bundle.putString("productType", productType);
                    bundle.putString("productId", productId);
                    bundle.putString("repaymentType", paybackMode);
                    bundle.putDouble("serviceFeeRate", monthRate);
                    bundle.putString("lastProductUpdateTime", lastProductUpdateTime);
                    bundle.putString("gradeId", gradeId);
                    bundle.putInt("daysPerMonth", daysPerMonth);//日利率
                    bundle.putString("serviceFeeSetting", serviceFeeSetting);
                    bundle.putInt("purpose",loanUsageInt);
                    //直接下一步
                    startActivity(ApplyProgressActivity.class, bundle);
                } else {
                    ToastUtil.getInstant().show(ApplyCashActivity.this, response.getDescription());

                    //画面跳转
                    if(response.getDescription().equals("紧急联系人不足3人") ||
                            response.getDescription().equals("查不到紧急联系人信息")){

                        final AlertDialog alertDialog = new AlertDialog.Builder(ApplyCashActivity.this)
                                .setTitle("提示")
                                .setMessage("紧急联系人不全，是否立即去补全？")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        Bundle bundle = new Bundle();
                                        //bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                        bundle.putBoolean("isConfirml",true);
                                        startActivity(ContractInfoActivity.class,bundle);
                                    }
                                }).setCancelable(false).create();
                        alertDialog.show();
                    }
                    //画面跳转
                    if(response.getDescription().equals("查不到该用户补录信息")){

                        final AlertDialog alertDialog = new AlertDialog.Builder(ApplyCashActivity.this)
                                .setTitle("提示")
                                .setMessage("贷款信息不全，是否立即去补全？")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        startActivity(UserSupplActivity.class);
                                    }
                                }).setCancelable(false).create();
                        alertDialog.show();
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();

                ToastUtil.getInstant().show(ApplyCashActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void loanCash() {
        show();
        HttpParams params = new HttpParams();
        params.put("applyAmount", loanAmount);
        params.put("deadlinekey", deadlinekey);
        params.put("deadline", paybackPeriod);
        params.put("unit", unit);
        params.put("productType", productType);
        params.put("productId", productId);
        params.put("repaymentType", paybackMode);
        params.put("serviceFeeRate", monthRate);
        params.put("lastProductUpdateTime", lastProductUpdateTime);
        params.put("gradeId", gradeId);
        params.put("daysPerMonth", daysPerMonth);//日利率
        params.put("serviceFeeSetting", serviceFeeSetting);
        params.put("purpose",loanUsageInt);

        DMOKHttpUtils.getInstance().post(this, DMConstant.Config.BASE_USER + "/project/" + LoanType.getNameByType(productType) + DMConstant.Config.V + "/insert.do", params, new RequestCallBack<SubmitLoanBean>() {
            @Override
            public void onSuccess(JsonResult<SubmitLoanBean> response) {
                dismiss();

                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    SubmitLoanBean submitLoanBean = response.getObject();

                    if (null != submitLoanBean) {
                        Bundle bundle = new Bundle();
                        bundle.putString(SubmitLoanBean.LOAN_AMOUNT, submitLoanBean.getApplyAmount());
                        bundle.putString(ConstantAppInfo.PROJECT_ID, submitLoanBean.getProjectId());
                        bundle.putInt(ConstantAppInfo.PROJECT_TYPE, submitLoanBean.getProductType());
                        if (ProjectStatus.SHZ.equals(String.valueOf(submitLoanBean.getStatus()))) {
                            bundle.putString(ConstantAppInfo.PROJECT_STATUS, ProjectStatus.SHZ);
                            startActivity(LoanProgressActivity.class, bundle, true);
                        } else {
                            startActivity(ConfirmAgreementActivity.class, bundle);
                        }
                    }

                   /* if (null != submitLoanBean) {
                        Bundle bundle = new Bundle();
                        bundle.putString(SubmitLoanBean.LOAN_AMOUNT, submitLoanBean.getApplyAmount());
                        bundle.putString(ConstantAppInfo.PROJECT_ID, submitLoanBean.getProjectId());
                        bundle.putInt(ConstantAppInfo.PROJECT_TYPE, submitLoanBean.getProductType());
                        if (ProjectStatus.SHZ.equals(String.valueOf(submitLoanBean.getStatus()))) {
                            bundle.putString(ConstantAppInfo.PROJECT_STATUS, ProjectStatus.SHZ);
                            startActivity(LoanProgressActivity.class, bundle, true);
                        } else {
                            startActivity(ConfirmAgreementActivity.class, bundle);
                        }
                    }*/
                } else {
                    ToastUtil.getInstant().show(ApplyCashActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();

                ToastUtil.getInstant().show(ApplyCashActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private boolean checkJinbaoLoan() {
        if (productConfigBean == null) {
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.data_error));
            return false;
        }

        if (loanAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
            return false;
        }

        if (loanAmount > loanLimit) {
            ToastUtil.getInstant().show(this, "借款金额不能大于最大借款额度");
            return false;
        }

        if (TextUtils.isEmpty(paybackMode)) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
            return false;
        }
        if (0 == paybackPeriod) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_deadline));
            return false;
        }

        if(-1 == loanUsageInt){
            ToastUtil.getInstant().show(this, "请选择" + getString(R.string.loan_usage));
            return false;
        }

        if (!ckProtocol.isChecked()) {
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.msg_read_loan_agreement));
            return false;
        }
        return true;
    }

    //跳转到借款计划
    private void checkAndgotoLoanPlan() {
        if (!checkLoanPlan()) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putDouble("applyAmount", loanAmount); //借款金额
        bundle.putString("repaymentType", paybackMode);// //还款方式
        bundle.putString("deadline", String.valueOf(paybackPeriod));    //借款期限
        bundle.putString("reta", monthRate + ""); //利率（月）
        bundle.putString("serviceFeeSetting", productConfigBean.getProductInfo().getServiceFeeSetting()); // 是否是固定金额
        if ("0".equals(paybackMode)) {
            bundle.putString("strRate", getString(R.string.Label_daily_interest_rate) + strRate); //天
        } else {
            bundle.putString("strRate", getString(R.string.Label_monthly_interest_rate) + strRate); //月
//            bundle.putString("strRate",strRate); //2018.1.31.新增鸿胜自己代码
        }
        bundle.putDouble("allInterestRate", allInterestRate); //总利息
        startActivity(RepayPlanActivity.class, bundle);
    }

    private boolean checkLoanPlan() {
        if (loanAmount == 0) {
            ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
            return false;
        }
        if (TextUtils.isEmpty(paybackMode)) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
            return false;
        }
        if (0 == paybackPeriod) {
            ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_deadline));
            return false;
        }

        if (StringUtils.isEmptyOrNull(monthRate + "")) {
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.data_error));
            return false;
        }
        return true;
    }

    private void clickDialog(int id) {
        CommonDialog.Builder builder = new CommonDialog.Builder();
        builder.setContext(this).setOnItemSelectListener(this);
        switch (id) {
            case R.id.oll_payback_type:
                builder.setData(repaymentTypeList).setFlag(PAYBACK_METHOD).setTitle(getString(R.string.payback_mode));
                break;
            case R.id.oll_apply_date:
                if (loanAmount == 0) {
                    ToastUtil.getInstant().show(this, getString(R.string.msg_input_loan_amount));
                    return;
                }
                if (paybackMode == null) {
                    ToastUtil.getInstant().show(this, getString(R.string.please_select_repay_mode));
                    return;
                }
                List<IPickerViewData> deadLineList = handleApplyPeriod(paybackMode);
                if (deadLineList == null) deadLineList = new ArrayList<>();
                builder.setData(deadLineList).setFlag(PAYBACK_DEADLINE).setTitle(getString(R.string.repay_deadline));
                break;
            case R.id.oll_loan_usage:               //贷款用途
                builder.setData(getLoanUsageData()).setFlag(LOAN_USAGE).setTitle(getString(R.string.loan_usage));

                break;
        }
        builder.build().showPickerView();
    }


    public List<LoanUsageBean> getLoanUsageData(){
        List<LoanUsageBean> list = new ArrayList<>();

        LoanUsageBean loanUsageBean = new LoanUsageBean();
        loanUsageBean.setName("旅游");
        loanUsageBean.setValue(0);

        LoanUsageBean educationBean = new LoanUsageBean();
        educationBean.setName("教育");
        educationBean.setValue(1);

        LoanUsageBean deviceBean = new LoanUsageBean();
        deviceBean.setName("电器");
        deviceBean.setValue(2);

        LoanUsageBean decorationBean = new LoanUsageBean();
        decorationBean.setName("装修");
        decorationBean.setValue(3);

        list.add(loanUsageBean);
        list.add(educationBean);
        list.add(deviceBean);
        list.add(decorationBean);
        return list;
    }




    private List handleApplyPeriod(String paybackMode) {
        if ("0".equals(paybackMode)) {
            return getDayList();
        } else {
            return productConfigBean.getDeadlineMonthList();
        }
    }

    private List getDayList() {
        List dayList = new ArrayList();
        List<ProductConfigBean.DeadlineDayListBean> deadlineDayList = productConfigBean.getDeadlineDayList();
        if (null != deadlineDayList && !deadlineDayList.isEmpty()) {
            ProductConfigBean.DeadlineDayListBean deadlineDayListBean = deadlineDayList.get(0);
            String month = deadlineDayListBean.getMonth();
            serviceFeeRate = String.valueOf(deadlineDayListBean.getMonthRate());
            monthRate = deadlineDayListBean.getMonthRate();
            gradeId = deadlineDayListBean.getGradeId();
            unit = deadlineDayListBean.getUnit();
            deadlinekey = month;    //对于月就是 "1"；对于日 "1-20"///
            dailyRate = monthRate / productConfigBean.getDaysPerMonth();

            strRate = FormatUtil.get2String(dailyRate * 100) + "%";
            ollInterestRate.setRightContent(strRate);//日利率
            ollInterestRate.setLeftContent(getString(R.string.Label_daily_interest_rate));

            if (null != month && month.contains("-")) {
                String[] split = month.split("-");
                int startDay = StringUtils.toInt(split[0], 0);
                int endDay = StringUtils.toInt(split[1], 0);
                for (int i = startDay; i <= endDay; i++) {
                    dayList.add(new ApplyLoanDayListBean(i));
                }
            }
        }
        return dayList;
    }

    @Override
    public void onItemSelect(IPickerViewData data, int position, int flag) {
        switch (flag) {
            case PAYBACK_METHOD://还款方式
                ProductConfigBean.RepaymentTypeBean repaymentTypeBean = (ProductConfigBean.RepaymentTypeBean) data;
                paybackMode = repaymentTypeBean.getType();
                ollPaybackMethod.setRightContent(repaymentTypeBean.getName());
                reset();
                break;
            case PAYBACK_DEADLINE://还款期限
                handlePayback(data);
                break;
            case LOAN_USAGE:            //贷款用途
                LoanUsageBean loanUsageBean = (LoanUsageBean)data;
                if(loanUsageBean != null){
                    ollloanUsage.setRightContent(loanUsageBean.getName());
                    loanUsageInt = loanUsageBean.getValue();
                }else {
                    ollloanUsage.setRightContent("");
                    loanUsageInt = -1;
                }
                break;
        }
    }

    private void handlePayback(IPickerViewData data) {
        //月
        if (!"0".equals(paybackMode)) {
            ProductConfigBean.DeadlineMonthListBean monthListBean = (ProductConfigBean.DeadlineMonthListBean) data;
            paybackPeriod = monthListBean.getMonth();
            monthRate = monthListBean.getMonthRate();
            ollApplyDate.setRightContent(paybackPeriod + getString(R.string.one_months));
            strRate = FormatUtil.get2String(monthRate * 100) + "%";
            ollInterestRate.setRightContent(strRate);//月利率
            ollInterestRate.setLeftContent(getString(R.string.Label_monthly_interest_rate));

            serviceFeeRate = String.valueOf(monthRate);
            deadlinekey = String.valueOf(monthListBean.getMonth());
            gradeId = monthListBean.getGradeId();
            unit = "1";
        } else {
            //天
            ApplyLoanDayListBean applyLoanDayListBean = (ApplyLoanDayListBean) data;
            paybackPeriod = applyLoanDayListBean.getDays();
            ollApplyDate.setRightContent(paybackPeriod + getString(R.string.day));
        }
        initInterest();
    }

    /**
     * 总利息计算
     */
    private void initInterest() {
        try {
            switch (paybackMode) {
                case "0"://一次性还款付息
                    serviceFeeSetting = productConfigBean.getProductInfo().getServiceFeeSetting();
                    if ("1".equals(serviceFeeSetting)) { //0代表固定金额，1代表%
                        // serviceFeeSetting == 1的时候）  //本金×（1+ 日利率 × 月份）
//                        interest = money  * ( 1 + self.rate * month);
                        allInterestRate = loanAmount * (dailyRate * paybackPeriod);
                    } else {
                        // serviceFeeSetting == 0的时候）
//                        interest = self.rate * month;
                        allInterestRate = dailyRate * paybackPeriod;
                    }
                    break;
                case "1"://等额本息
                    // 本金×月利率×（1+月利率）月数÷[（1+月利率）月数—1]   *   月数
//                   interest = (money * self.rate * pow(1 + self.rate, month) / (pow(1 + self.rate, month) - 1)) * month;
                    allInterestRate = loanAmount * monthRate * Math.pow((1 + monthRate), paybackPeriod) / (Math.pow((1 + monthRate), paybackPeriod) - 1) * paybackPeriod - loanAmount;
                    break;
                case "2"://等额本金
                    // （还款月数+1）×贷款额×月利率/2 + 贷款额
//                    interest = (month + 1) * money  * self.rate/2.0 + money;
                    allInterestRate = (paybackPeriod + 1) * loanAmount * monthRate / 2;
                    break;
                case "3"://每月付息，到期还本
                    //       interest = month * self.rate * money  + money ;
                    allInterestRate = paybackPeriod * monthRate * loanAmount;
                    break;
            }
            ollAllInterestRate.setRightContent(allInterestRate);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.getInstant().show(ApplyCashActivity.this, getString(R.string.data_error));
        }
    }

    private void reset() {
        paybackPeriod = 0;
        gradeId = "";
        serviceFeeRate = "";
        unit = "";
        deadlinekey = "";
        allInterestRate = 0.00;
        ollApplyDate.setRightContent(getString(R.string.please_loan_dateline));
        ollAllInterestRate.setRightContent("0.00");
        ollInterestRate.setRightContent("0.00%");
        ollInterestRate.setLeftContent(getString(R.string.Label_monthly_interest_rate));
    }
}
